import 'dart:math';

import 'package:acgn_pioneer/components/book-item/book1.dart';
import 'package:acgn_pioneer/components/circle_tag.dart';
import 'package:acgn_pioneer/components/text_highlight_component.dart';
import 'package:acgn_pioneer/models/sort_comic_model.dart';
import 'package:acgn_pioneer/pages/reader/reader_page_main.dart';
import 'package:acgn_pioneer/utils/pop_util.dart';
import 'package:flutter/widgets.dart';
import '../../public.dart';

/// 分类-搜索tab
class SortResultPage extends StatefulWidget {
  SortResultPage({Key key}) : super(key: key);

  @override
  SortResultPageState createState() => SortResultPageState();
}

class SortResultPageState extends State<SortResultPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  /// 显示类型 1：热门，2：漫画，3：快捷搜索
  var type = 1;
  List<String> lstHistorySeach = []; // 搜索历史
  List<SortComicModel> lstTopSeach = []; // 热门搜索
  List<SortComicModel> lstMainSearch = []; // 关键词搜索
  String searchKey = ''; // 搜索key
  String searchHistoryKey = 'SortSearchHistory';

  TextEditingController textEditingController = TextEditingController();

  @override
  bool get wantKeepAlive => true;

  var subPop;

  @override
  void initState() {
    super.initState();
    getTopSearch();
    getHistoryList();
  }

  getHistoryList() {
    var re = SpUtil.getStringList(searchHistoryKey);
    if (re.length > 0) {
      lstHistorySeach = re;
    }
  }

  getTopSearch() async {
    lstTopSeach = await SortService.getTopSearch();
    setState(() {});
  }

  @override
  void dispose() {
    textEditingController.dispose();
    subPop.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
        width: ScreenUtil.getInstance().screenWidth,
        child: Column(children: [
          buildInput(),
          // DataUtil.noData('暂无搜索结果')
          buildHistoryList(),
          Expanded(child: buildContentView())
        ]),
        padding: EdgeInsets.only(left: 16, right: 16));
  }

  buildContentView() {
    if (type == 1) {
      return buildHotList();
    }
    if (type == 2) {
      return buildComicList();
    }
    return buildFastList();
  }

  ///  输入框
  buildInput() {
    return Container(
        width: Rem(343),
        height: Rem(32),
        margin: EdgeInsets.only(top: Rem(16)),
        padding: EdgeInsets.only(left: Rem(16)),
        decoration: BoxDecoration(
            color: ColorUtil.rgba(255, 255, 255, 0.15),
            borderRadius: BorderRadius.all(Radius.circular(20))),
        child: Row(
          children: [
            SVG.svg('input_search'),
            Container(
                alignment: Alignment.center,
                width: Rem(280),
                height: Rem(30),
                child: TextField(
                    controller: textEditingController,
                    onSubmitted: (String value) {
                      type = 2;
                      searchKey = value;
                      getSortList();
                      saveSearchHistory();
                    },
                    onChanged: (String value) {
                      type = 3;
                      searchKey = value;
                      getSortList();
                    },
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                    ),
                    decoration: InputDecoration(
                      focusColor: ColorUtil.rgba(255, 255, 255, 0.7),
                      hintText: '斗罗大陆',
                      hintStyle:
                          TextStyle(color: ColorUtil.rgba(255, 255, 255, 0.3)),
                      contentPadding: EdgeInsets.only(top: -18, left: 4),
                      errorBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                    ))),
            searchKey != ''
                ? GestureDetector(
                    child: SVG.svg('input_close'),
                    onTap: () {
                      textEditingController.clear();
                      this.searchKey = '';
                      getSortList();
                    },
                  )
                : Container(),
          ],
        ));
  }

  saveSearchHistory() {
    if (searchKey == '' || lstHistorySeach.indexOf(searchKey) != -1) {
      return;
    }
    lstHistorySeach.add(searchKey);
    SpUtil.putStringList(searchHistoryKey, lstHistorySeach);
    setState(() {});
  }

  clearSearchHistory() {
    lstHistorySeach.clear();
    SpUtil.putStringList(searchHistoryKey, lstHistorySeach);
    setState(() {});
  }

  /// 联想列表
  getSortList() async {
    if (searchKey == '') {
      type = 1;
      lstMainSearch = [];
    } else {
      lstMainSearch = await SortService.getSortlist(key: searchKey);
    }
    setState(() {});
  }

  /// 热门
  buildHotList() {
    if (lstTopSeach == null) {
      return Container();
    }
    return Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(top: 20),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            '热门搜索',
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          SizedBox(height: 8),
          Expanded(
              child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 130 / 74,
                      crossAxisSpacing: 18,
                      mainAxisSpacing: 9),
                  itemCount: lstTopSeach.length,
                  itemBuilder: (BuildContext context, int index) {
                    var row = lstTopSeach[index];
                    return GestureDetector(
                      onTap: () {
                        showPopComic(row.comicId,
                            lstTopSeach.map((e) => e.comicId).toList());
                      },
                      child: Row(children: [
                        ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: ImagesNetworkComponent(row.coverImg,
                                width: 56, height: 73)),
                        Expanded(
                            child: Container(
                          padding: EdgeInsets.only(left: 6),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                  margin: EdgeInsets.only(bottom: 4),
                                  child: Text(
                                    row.comicName,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 12),
                                  )),
                              Row(
                                children: buildTag(row.sortTypeList),
                              )
                            ],
                          ),
                        ))
                      ]),
                    );
                  }))
        ]));
  }

  showPopComic(int comicId, List<dynamic> comicIds) {
    PopUtil.showSlidePop(
        context: context,
        child: ReaderPageMain(
            comicIds: comicIds, comicId: comicId, isPopNested: true));
  }

  /// 构建标签
  buildTag(List<dynamic> lstTag) {
    List<Widget> lst = [];
    var len = min(lstTag.length, 2);
    for (var i = 0; i < len; i++) {
      lst.add(Text(
        lstTag[i],
        style:
            TextStyle(color: ColorUtil.rgba(255, 255, 255, 0.6), fontSize: 12),
      ));
      if (i != len) {
        lst.add(SizedBox(width: 4));
      }
    }

    return lst;
  }

  /// 漫画
  buildComicList() {
    return Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(top: 20),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            '漫画',
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          SizedBox(height: 8),
          Expanded(
              child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 105 / 190,
                      crossAxisSpacing: Rem(14),
                      mainAxisSpacing: Rem(14)),
                  itemCount: lstMainSearch.length,
                  itemBuilder: (BuildContext context, int index) {
                    var comic = lstMainSearch[index];
                    return GestureDetector(
                        onTap: () {
                          showPopComic(comic.comicId,
                              lstMainSearch.map((e) => e.comicId).toList());
                        },
                        child: Book1Component(
                          cover: comic.coverImg,
                          title: comic.comicName,
                          desc: comic.lastChapterName,
                        ));
                  }))
        ]));
  }

  /// 快捷搜索
  buildFastList() {
    if (lstMainSearch.length == 0) {
      return Container();
    }
    return Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(top: 20),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            '快捷搜索',
            style: TextStyle(
                color: ColorUtil.rgba(255, 255, 255, 0.6), fontSize: 14),
          ),
          SizedBox(height: 10),
          Expanded(
              child: ListView.builder(
                  itemCount: lstMainSearch.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                        height: Rem(30),
                        child: GestureDetector(
                            onTap: () {
                              showPopComic(lstMainSearch[index].comicId,
                                  lstMainSearch.map((e) => e.comicId).toList());
                            },
                            child: TextHighLightComponent(
                                overflow: TextOverflow.ellipsis,
                                text: lstMainSearch[index].comicName,
                                term: searchKey,
                                textStyle: TextStyle(
                                    color: Colors.white, fontSize: 14),
                                textStyleHighlight: TextStyle(
                                    color: ColorUtil.rgba(255, 215, 59, 1),
                                    fontSize: 14))));
                  }))
        ]));
  }

  /// 搜索历史
  buildHistoryList() {
    if (type != 1 || lstHistorySeach.length == 0) {
      return Container();
    }
    return Container(
        margin: EdgeInsets.only(top: 20),
        child: Column(children: [
          Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(
              '搜索历史',
              style: TextStyle(color: Colors.white, fontSize: 14),
            ),
            GestureDetector(
                onTap: () {
                  clearSearchHistory();
                },
                child: Text(
                  '清空',
                  style: TextStyle(
                      color: ColorUtil.rgba(255, 255, 255, 0.61), fontSize: 14),
                ))
          ]),
          Container(
              alignment: Alignment.topLeft,
              margin: EdgeInsets.only(top: 16),
              child: Wrap(children: buildHistoryTags()))
        ]));
  }

  buildHistoryTags() {
    List<Widget> lst = [];
    lstHistorySeach.forEach((String str) {
      lst.add(GestureDetector(
          onTap: () {
            textEditingController.text = str;
            searchKey = str;
            type = 2;
            getSortList();
          },
          child: CircleTag(
              fontSize: 12,
              borderRadius: BorderRadius.all(Radius.circular(12)),
              padding: EdgeInsets.only(top: 6, right: 12, bottom: 6, left: 12),
              text: str,
              margin: EdgeInsets.only(right: 14, bottom: 10),
              textColor: ColorUtil.rgba(255, 255, 255, 0.6),
              bgColor: ColorUtil.rgba(40, 40, 56, 1))));
    });
    return lst;
  }
}
